/**
 * Copyright (c) 2011-9-23 WKM and/or its affiliates. 
 * Use is subject to license terms.
 * All rights reserved.
 */
package org.wkm.definition;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wkm.util.Configuration;
import org.wkm.util.Home;

import com.ice.jni.registry.NoSuchKeyException;
import com.ice.jni.registry.NoSuchValueException;
import com.ice.jni.registry.RegStringValue;
import com.ice.jni.registry.Registry;
import com.ice.jni.registry.RegistryException;
import com.ice.jni.registry.RegistryKey;

/**
 * RegistryUtil 采用开源项目JRegistrykey进行了注册表的操作，其官方地址如下:
 * http://sourceforge.net/projects/jregistrykey
 * 其中对外提供了对注册表的增、删、查功能的API
 * @version 1.0 2011-12-19
 * @author WUKUNMENG
 */
public class RegistryUtil {

	public static String DEFAULT_FOLDER = "SOFTWARE";

	public static String DEFAULT_SUB_NODE = "Microsoft\\Windows\\CurrentVersion\\Run";

	public static String DEFAULT_KEY = "WKMTimer";
	
	private static Logger logger = LoggerFactory.getLogger(RegistryUtil.class);
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		RegistryUtil.test();
		 setValue("SOFTWARE", "Microsoft\\Windows\\CurrentVersion\\Run", "test",
				"D:\\other\\cmd.bat");
		//
		// deleteValue("SOFTWARE", "Microsoft\\Windows\\CurrentVersion\\Run",
		// "test");

	}

	static {
		try {
			File file = new File(Home.getPath(Configuration.REGISTRY_DLL));
			logger.info("查找文件：" + Home.getPath(Configuration.REGISTRY_DLL));
			logger.info("查找文件：" + Configuration.REGISTRY_DLL);
			if (file.exists()) {
				logger.info("文件找到，设置路径：" + file.getParentFile().getCanonicalPath());
				SystemLibraryPath.addLibraryPath(file.getParentFile().getCanonicalPath());
			} else {
				file = new File(Home.getHomePath() + File.separator
						+ Configuration.REGISTRY_DLL);
				if (file.exists()) {
					logger.info("文件找到，设置路径：" + file.getParentFile().getCanonicalPath());
					SystemLibraryPath.addLibraryPath(file.getParentFile().getCanonicalPath());
				} else {
					logger.info("未查找到文件：" + Configuration.REGISTRY_DLL);
				}
			}
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.info("查找文件失败：" + Configuration.REGISTRY_DLL);
			logger.info("原因：" + e.getMessage());
		}

	}

	public static void test() {
		System.out.println("-----");
	}

	private RegistryUtil() {
		// TODO static methods
	}

	public static boolean isSetAutoRun(String key) {
		String value = getValue(DEFAULT_FOLDER,DEFAULT_SUB_NODE, key);
		return value != null;
	}

	/**
	 * 取消开机自启动
	 * 
	 * @param key
	 *            键
	 * @return
	 */
	public static boolean cancelAutoRun(String key) {
		return deleteValue(DEFAULT_FOLDER,DEFAULT_SUB_NODE, key);
	}

	/**
	 * 设置自动重启项
	 * 
	 * @param key
	 *            键
	 * @param value
	 *            值
	 * @return
	 */
	public static boolean setAutoRun(String key, String value) {
		return setValue(DEFAULT_FOLDER, DEFAULT_SUB_NODE,key, value);
	}

	/**
	 * 把信息存储到注册表HKEY_LOCAL_MACHINE下的某个节点的某一变量中，有则修改，无则创建
	 * 
	 * @param folder
	 * @param subKeyNode
	 * @param subKeyName
	 * @param subKeyValue
	 * @return
	 */
	public static boolean setValue(String folder, String subKeyNode,
			String subKeyName, String subKeyValue) {
		try {
			RegistryKey software = Registry.HKEY_LOCAL_MACHINE
					.openSubKey(folder);
			RegistryKey subKey = software.createSubKey(subKeyNode, "");
			subKey
					.setValue(new RegStringValue(subKey, subKeyName,
							subKeyValue));
			subKey.closeKey();
			return Boolean.TRUE;
		} catch (NoSuchKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("No Key Exception" + e.getMessage());
		} catch (RegistryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("RegistryException:" + e.getMessage());
		}
		return Boolean.FALSE;
	}

	/**
	 * 删除注册表中某节点下的某个变量
	 * 
	 * @param folder
	 * @param subKeyNode
	 * @param subKeyName
	 * @return
	 */
	public static boolean deleteValue(String folder, String subKeyNode,
			String subKeyName) {

		try {
			RegistryKey software = Registry.HKEY_LOCAL_MACHINE
					.openSubKey(folder);
			RegistryKey subKey = software.createSubKey(subKeyNode, "");
			subKey.deleteValue(subKeyName);
			software.closeKey();
			return Boolean.TRUE;
		} catch (NoSuchKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("No Key Exception" + e.getMessage());
		} catch (RegistryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("RegistryException:" + e.getMessage());
		}

		return Boolean.FALSE;
	}

	/**
	 * 删除注册表中某节点下的某节点
	 * 
	 * @param folder
	 * @param subKeyNode
	 * @return
	 */
	public static boolean deleteSubKey(String folder, String subKeyNode) {
		try {
			RegistryKey software = Registry.HKEY_LOCAL_MACHINE
					.openSubKey(folder);
			software.deleteSubKey(subKeyNode);
			software.closeKey();
			return true;
		} catch (NoSuchKeyException e) {
			logger.warn("No Key Exception" + e.getMessage());
		} catch (RegistryException e) {
			e.printStackTrace();
			logger.error("RegistryException:" + e.getMessage());
		}
		return false;
	}

	/**
	 * 打开注册表项并读出相应的变量名的值
	 * 
	 * @param folder
	 * @param subKeyNode
	 * @param subKeyName
	 * @return
	 */
	public static String getValue(String folder, String subKeyNode,
			String subKeyName) {

		String value = null;
		try {
			RegistryKey software = Registry.HKEY_LOCAL_MACHINE
					.openSubKey(folder);
			RegistryKey subKey = software.openSubKey(subKeyNode);
			value = subKey.getStringValue(subKeyName);
			software.closeKey();
			return value;
		} catch (NoSuchKeyException e) {
			// TODO Auto-generated catch block
			logger.warn("No Key Exception" + e.getMessage());
			return null;
		} catch (NoSuchValueException e) {
			// TODO Auto-generated catch block
			logger.warn("No Value Exception" + e.getMessage());
			return null;
		} catch (RegistryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("RegistryException:" + e.getMessage());
		}
		return value;
	}
}
